<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="订单编号">
                <a-input v-model="queryParam.orderSn" placeholder="请输入订单编号"/>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="订单状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="">
                  <a-select-option value="">全部</a-select-option>
                  <a-select-option value="pending">待处理</a-select-option>
                  <a-select-option value="assigned">已分配</a-select-option>
                  <a-select-option value="in_transit">运输中</a-select-option>
                  <a-select-option value="completed">已完成</a-select-option>
                  <a-select-option value="cancelled">已取消</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="紧急程度">
                  <a-select v-model="queryParam.urgency" placeholder="请选择">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="low">低</a-select-option>
                    <a-select-option value="medium">中</a-select-option>
                    <a-select-option value="high">高</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="场景模式">
                  <a-select v-model="queryParam.sceneMode" placeholder="请选择">
                    <a-select-option value="">全部</a-select-option>
                    <a-select-option value="normal">普通配送</a-select-option>
                    <a-select-option value="medical_emergency">医疗急救</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="创建时间">
                  <a-range-picker v-model="queryParam.createdAt" style="width: 100%" />
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <div class="table-operator">
        <a-button type="primary" icon="plus" @click="handleAdd">新增订单</a-button>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <a-menu slot="overlay">
            <a-menu-item key="1" @click="handleBatchAssign"><a-icon type="rocket" />批量分配</a-menu-item>
            <a-menu-item key="2" @click="handleBatchCancel"><a-icon type="stop" />批量取消</a-menu-item>
          </a-menu>
          <a-button style="margin-left: 8px">
            批量操作 <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="orderId"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <span slot="urgency" slot-scope="text">
          <a-tag :color="urgencyColor(text)">{{ urgencyText(text) }}</a-tag>
        </span>
        <span slot="sceneMode" slot-scope="text">
          <a-badge :status="text === 'medical_emergency' ? 'error' : 'default'" :text="text === 'medical_emergency' ? '医疗急救' : '普通配送'" />
        </span>
        <span slot="status" slot-scope="text">
          <a-badge :status="statusType(text)" :text="statusText(text)" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleView(record)">查看</a>
            <a-divider type="vertical" />
            <a @click="handleEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link">
                更多 <a-icon type="down" />
              </a>
              <a-menu slot="overlay">
                <a-menu-item v-if="record.status === 'pending'" @click="handleAssign(record)">
                  <a-icon type="rocket" />分配无人机
                </a-menu-item>
                <a-menu-item v-if="['pending', 'assigned'].includes(record.status)" @click="handleCancelOrder(record)">
                  <a-icon type="stop" />取消订单
                </a-menu-item>
                <a-menu-item v-if="record.status === 'assigned'" @click="handleStart(record)">
                  <a-icon type="play-circle" />开始配送
                </a-menu-item>
                <a-menu-item v-if="record.status === 'in_transit'" @click="handleComplete(record)">
                  <a-icon type="check-circle" />完成配送
                </a-menu-item>
                <a-menu-item @click="handleTrack(record)">
                  <a-icon type="environment" />追踪订单
                </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </span>
      </s-table>

      <!-- 订单详情弹窗 -->
      <a-modal
        :title="modalTitle"
        :width="800"
        :visible="visible"
        :confirmLoading="confirmLoading"
        @ok="handleOk"
        @cancel="handleCancel"
      >
        <a-form :form="form" v-bind="formLayout">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="订单编号">
                <a-input
                  v-decorator="[
                    'orderSn',
                    {
                      rules: [{ required: true, message: '请输入订单编号' }],
                      initialValue: currentOrder.orderSn
                    }
                  ]"
                  :disabled="currentOrder.orderId !== undefined"
                  placeholder="系统自动生成"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="用户ID">
                <a-input
                  v-decorator="[
                    'userId',
                    {
                      rules: [{ required: true, message: '请输入用户ID' }],
                      initialValue: currentOrder.userId
                    }
                  ]"
                  placeholder="请输入用户ID"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="货物重量(kg)">
                <a-input-number
                  v-decorator="[
                    'goodsWeight',
                    {
                      rules: [{ required: true, message: '请输入货物重量' }],
                      initialValue: currentOrder.goodsWeight
                    }
                  ]"
                  :min="0.1"
                  :max="100"
                  :step="0.1"
                  style="width: 100%"
                  placeholder="请输入货物重量"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="紧急程度">
                <a-select
                  v-decorator="[
                    'urgency',
                    {
                      rules: [{ required: true, message: '请选择紧急程度' }],
                      initialValue: currentOrder.urgency || 'medium'
                    }
                  ]"
                  placeholder="请选择紧急程度"
                >
                  <a-select-option value="low">低</a-select-option>
                  <a-select-option value="medium">中</a-select-option>
                  <a-select-option value="high">高</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="场景模式">
                <a-select
                  v-decorator="[
                    'sceneMode',
                    {
                      rules: [{ required: true, message: '请选择场景模式' }],
                      initialValue: currentOrder.sceneMode || 'normal'
                    }
                  ]"
                  @change="handleSceneModeChange"
                  placeholder="请选择场景模式"
                >
                  <a-select-option value="normal">普通配送</a-select-option>
                  <a-select-option value="medical_emergency">医疗急救</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="收货地址ID">
                <a-input
                  v-decorator="[
                    'addressId',
                    {
                      rules: [{ required: true, message: '请输入收货地址ID' }],
                      initialValue: currentOrder.addressId
                    }
                  ]"
                  placeholder="请输入收货地址ID"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item v-if="showHospitalInfo" label="医院信息">
            <a-textarea
              v-decorator="[
                'hospitalInfo',
                {
                  rules: [{ required: true, message: '请输入医院信息' }],
                  initialValue: currentOrder.hospitalInfo ? JSON.stringify(currentOrder.hospitalInfo) : ''
                }
              ]"
              :rows="4"
              placeholder="请输入医院信息(JSON格式，包含名称、地址、联系方式)"
            />
          </a-form-item>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="目的地经度">
                <a-input
                  v-decorator="[
                    'destinationLng',
                    {
                      rules: [{ required: true, message: '请输入目的地经度' }],
                      initialValue: currentOrder.destinationCoords ? currentOrder.destinationCoords.x : ''
                    }
                  ]"
                  placeholder="请输入目的地经度"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="目的地纬度">
                <a-input
                  v-decorator="[
                    'destinationLat',
                    {
                      rules: [{ required: true, message: '请输入目的地纬度' }],
                      initialValue: currentOrder.destinationCoords ? currentOrder.destinationCoords.y : ''
                    }
                  ]"
                  placeholder="请输入目的地纬度"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item v-if="currentOrder.orderId" label="订单状态">
            <a-select
              v-decorator="[
                'status',
                {
                  rules: [{ required: true, message: '请选择订单状态' }],
                  initialValue: currentOrder.status || 'pending'
                }
              ]"
              placeholder="请选择订单状态"
            >
              <a-select-option value="pending">待处理</a-select-option>
              <a-select-option value="assigned">已分配</a-select-option>
              <a-select-option value="in_transit">运输中</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item v-if="currentOrder.orderId && ['assigned', 'in_transit', 'completed'].includes(form.getFieldValue('status'))" label="无人机ID">
            <a-input
              v-decorator="[
                'droneId',
                {
                  initialValue: currentOrder.droneId
                }
              ]"
              placeholder="请输入无人机ID"
            />
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components'

export default {
  name: 'OrderList',
  components: {
    STable
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表格列定义
      columns: [
        {
          title: '#',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '订单编号',
          dataIndex: 'orderSn',
          sorter: true
        },
        {
          title: '用户ID',
          dataIndex: 'userId'
        },
        {
          title: '无人机ID',
          dataIndex: 'droneId'
        },
        {
          title: '货物重量(kg)',
          dataIndex: 'goodsWeight',
          sorter: true
        },
        {
          title: '紧急程度',
          dataIndex: 'urgency',
          scopedSlots: { customRender: 'urgency' }
        },
        {
          title: '场景模式',
          dataIndex: 'sceneMode',
          scopedSlots: { customRender: 'sceneMode' }
        },
        {
          title: '订单状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          sorter: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '150px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法
      loadData: parameter => {
        console.log('loadData.parameter', parameter)
        // 模拟后端数据
        const data = {
          pageSize: parameter.pageSize,
          pageNo: parameter.pageNo,
          totalCount: 100,
          data: Array(10).fill().map((_, index) => ({
            orderId: index + 1,
            userId: Math.floor(Math.random() * 1000) + 1,
            droneId: ['pending', 'cancelled'].includes(this.getRandomStatus()) ? null : Math.floor(Math.random() * 100) + 1,
            addressId: Math.floor(Math.random() * 500) + 1,
            orderSn: `ORD${String(index + 1001).padStart(6, '0')}`,
            goodsWeight: (Math.random() * 20 + 0.5).toFixed(2),
            urgency: ['low', 'medium', 'high'][Math.floor(Math.random() * 3)],
            sceneMode: Math.random() > 0.8 ? 'medical_emergency' : 'normal',
            hospitalInfo: Math.random() > 0.8 ? {
              name: '重庆医科大学附属第一医院',
              address: '重庆市渝中区袁家岗友谊路1号',
              contact: '023-12345678'
            } : null,
            destinationCoords: {
              x: 106.504962 + (Math.random() - 0.5) * 0.1,
              y: 29.533155 + (Math.random() - 0.5) * 0.1
            },
            status: this.getRandomStatus(),
            createdAt: moment().subtract(Math.floor(Math.random() * 30), 'days').format('YYYY-MM-DD HH:mm:ss'),
            updatedAt: moment().subtract(Math.floor(Math.random() * 10), 'days').format('YYYY-MM-DD HH:mm:ss')
          }))
        }
        return new Promise(resolve => {
          resolve({
            pageSize: data.pageSize,
            pageNo: data.pageNo,
            totalCount: data.totalCount,
            data: data.data
          })
        })
      },
      // 表单相关
      visible: false,
      confirmLoading: false,
      formLayout: {
        labelCol: { span: 6 },
        wrapperCol: { span: 18 }
      },
      form: this.$form.createForm(this),
      currentOrder: {},
      showHospitalInfo: false,
      // 选择行
      selectedRowKeys: [],
      selectedRows: []
    }
  },
  computed: {
    modalTitle () {
      return this.currentOrder.orderId ? '编辑订单' : '新增订单'
    },
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    // 获取随机状态
    getRandomStatus () {
      const statuses = ['pending', 'assigned', 'in_transit', 'completed', 'cancelled']
      const weights = [0.3, 0.2, 0.2, 0.2, 0.1] // 权重分布
      const random = Math.random()
      let sum = 0
      for (let i = 0; i < weights.length; i++) {
        sum += weights[i]
        if (random < sum) {
          return statuses[i]
        }
      }
      return statuses[0]
    },

    // 紧急程度颜色
    urgencyColor (urgency) {
      const colors = {
        low: 'blue',
        medium: 'orange',
        high: 'red'
      }
      return colors[urgency] || 'blue'
    },

    // 紧急程度文本
    urgencyText (urgency) {
      const texts = {
        low: '低',
        medium: '中',
        high: '高'
      }
      return texts[urgency] || '未知'
    },

    // 状态类型
    statusType (status) {
      const types = {
        pending: 'warning',
        assigned: 'processing',
        in_transit: 'processing',
        completed: 'success',
        cancelled: 'error'
      }
      return types[status] || 'default'
    },

    // 状态文本
    statusText (status) {
      const texts = {
        pending: '待处理',
        assigned: '已分配',
        in_transit: '运输中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return texts[status] || '未知'
    },

    // 切换高级搜索
    toggleAdvanced () {
      this.advanced = !this.advanced
    },

    // 选择行变化
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },

    // 新增订单
    handleAdd () {
      this.currentOrder = {}
      this.visible = true
      this.showHospitalInfo = false
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    // 查看订单
    handleView (record) {
      this.$router.push({ path: `/list/basic-list/${record.orderId}` })
    },

    // 编辑订单
    handleEdit (record) {
      this.currentOrder = { ...record }
      this.visible = true
      this.showHospitalInfo = record.sceneMode === 'medical_emergency'
      this.$nextTick(() => {
        this.form.resetFields()
      })
    },

    // 场景模式变化
    handleSceneModeChange (value) {
      this.showHospitalInfo = value === 'medical_emergency'
    },

    // 表单提交
    handleOk () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true
          console.log('表单数据:', values)

          // 处理医院信息
          if (values.hospitalInfo) {
            try {
              values.hospitalInfo = JSON.parse(values.hospitalInfo)
            } catch (e) {
              this.$message.error('医院信息格式不正确，请使用有效的JSON格式')
              this.confirmLoading = false
              return
            }
          }

          // 处理目的地坐标
          values.destinationCoords = {
            x: parseFloat(values.destinationLng),
            y: parseFloat(values.destinationLat)
          }
          delete values.destinationLng
          delete values.destinationLat

          // 模拟API请求
          setTimeout(() => {
            this.visible = false
            this.confirmLoading = false
            this.$message.success(this.currentOrder.orderId ? '修改成功' : '添加成功')
            this.$refs.table.refresh()
          }, 1000)
        }
      })
    },

    // 关闭表单
    handleCancel () {
      this.visible = false
    },

    // 取消订单 (将这个方法重命名为handleCancelOrder)
    handleCancelOrder (record) {
      this.$confirm({
        title: '取消订单',
        content: `确定要取消订单 ${record.orderSn} 吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('取消成功')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 分配无人机
    handleAssign (record) {
      this.$confirm({
        title: '分配无人机',
        content: `确定要为订单 ${record.orderSn} 分配无人机吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('分配成功')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 开始配送
    handleStart (record) {
      this.$confirm({
        title: '开始配送',
        content: `确定要开始配送订单 ${record.orderSn} 吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('配送已开始')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 完成配送
    handleComplete (record) {
      this.$confirm({
        title: '完成配送',
        content: `确定要将订单 ${record.orderSn} 标记为已完成吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('配送已完成')
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 追踪订单
    handleTrack (record) {
      this.$router.push({ path: '/map/implementation', query: { orderId: record.orderId } })
    },

    // 批量分配
    handleBatchAssign () {
      this.$confirm({
        title: '批量分配',
        content: `确定要为选中的 ${this.selectedRowKeys.length} 个订单分配无人机吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('批量分配成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh()
          }, 500)
        }
      })
    },

    // 批量取消
    handleBatchCancel () {
      this.$confirm({
        title: '批量取消',
        content: `确定要取消选中的 ${this.selectedRowKeys.length} 个订单吗？`,
        onOk: () => {
          // 模拟API请求
          setTimeout(() => {
            this.$message.success('批量取消成功')
            this.selectedRowKeys = []
            this.$refs.table.refresh()
          }, 500)
        }
        })
    }
  }
}
</script>

<style lang="less" scoped>
.table-operator {
  margin-bottom: 18px;
}
</style>
